<?php
namespace app\sso\middleware;

use app\common\service\JwtService;
use think\facade\Session;
use think\facade\Log;
use app\common\library\Auth as AuthService;

class JwtAuth
{
    public function handle($request, \Closure $next)
    {
        $request_url = $_SERVER['REQUEST_URI'];
        $pathinfo = explode('?',$request_url)[0];
        $pathinfo = strtolower($pathinfo);
        $pathinfo = str_replace('.html','',$pathinfo);
        $white_list = [
            '/sso/index/login',  // 登录页面
            '/sso/index/register',  // 注册页面
            '/sso/api/sendsmscode',  // 发送短信验证码接口
            '/sso/api/login',  // 登录接口
            '/sso/api/register',  // 注册接口
        ];
        
        if(in_array($pathinfo,['/sso/api/sendsmscode','/sso/api/login','/sso/api/register'])){
            try {
                $check = $request->checkToken('__token__');
                if(false === $check) {
                    throw new \Exception('csrf token 验证失败,请重试');
                }
            } catch (\Exception $e) {
                return json([
                    'code' => 401,  // 返回401未授权状态码
                    'msg'  => $e->getMessage(),  // 返回错误信息
                    'data' => ['token' => $request->buildToken('__token__', 'sha1')]
                ]);
            }
        }

        if(!in_array($pathinfo,$white_list)&&0){
            // 检查是否为登录接口，如果是则跳过验证            
            try {
                $token = $request->header('Authorization');
                $token = $token ? $token : $request->header('Access-Token');
                $token = $token ? $token : Session::get('token');
                $token = $token ? $token : $request->param('token');

                if (!$token) {
                    throw new \Exception('未提供认证信息');  // 如果token为空，抛出异常
                }
                
                $AuthService = new AuthService();
                $res = $AuthService->init($token);
                if(!$res){
                    throw new \Exception('token验证失败');  // 如果token为空，抛出异常
                }
                // 验证JWT
                $request->userInfo = $AuthService->validateUserToken();  // 将解码后的用户信息存入request对象
                $request->token = $token;  // 将解码后的用户信息存入request对象
                
            } catch (\Exception $e) {
                Log::error("JWT验证失败：" . $e->getMessage());  // 记录错误日志
                return json([
                    'code' => 401,  // 返回401未授权状态码
                    'msg'  => $e->getMessage(),  // 返回错误信息
                    'data' => null
                ]);
            }
        }
        return $next($request);  // 继续处理请求
    }
}
